/**
 * ...
 * @author Franco Ponticelli
 */

package uform.ui.comp;
import uform.property.IReadProperty;
import uform.property.Property;
import uform.ui.comp.Container;
import uform.ui.comp.Component;
import uform.property.IProperty;
import uform.ui.comp.Stack;
import hxevents.Notifier;

class StackItem extends Container
{
	public var child(default, null) : Component;
	public var index(default, null) : IReadProperty<Int>;
	public var stack(default, null) : Stack;
	var _index : Property<Int>;
	
	public function new(child : Component)
	{
		super();
		this.child = child;
		this.index = _index = new Property(-1);
		this.parent.onChange.add(_parentChange);
		this._parentFor(child);
	}
	
	override function _id()
	{
		return "" + index.get();
	}
	
	public function isFirst()
	{
		return index.get() == 0;
	}
	
	public function isLast()
	{
		if (null == stack)
			return false;
		else
			return index.get() == stack.length - 1;
	}
	
	public function isOdd()
	{
		var i = index.get();
		if (i < 0)
			return false;
		else
			return (i % 2) == 0;
	}
	
	public function isEven()
	{
		var i = index.get();
		if (i < 0)
			return false;
		else
			return (i % 2) != 0;
	}
	
	function _parentChange()
	{
		var old = parent.getOld();
		if (null != old)
		{
			_unwire(cast old);
		}
		if (parent.isNull())
		{
			if (null != _index)
				_index.set(-1);
			stack = null;
		} else {
			stack = cast parent.get();
			_wire();
			_index.set(stack.positionItem(this));
		}
	}
	
	function _wire()
	{
		stack.onInsert.add(_updateInsert);
		stack.onRemove.add(_updateRemove);
	}
	
	function _unwire(old : Stack)
	{
		if (null == old)
			return;
		old.onInsert.remove(_updateInsert);
		old.onRemove.remove(_updateRemove);
	}
	
	function _updateInsert(_)
	{
		_update();
	}
	
	function _updateRemove(_)
	{
		_update();
	}
	
	function _update()
	{
		if (null == stack)
		{
			_index.set( -1);
		} else {
			_index.set(stack.positionItem(this));
		}
	}

	override function remove(o : Component)
	{
		if (child == o)
		{
			_unwire(stack);
			super.remove(o);
			stack = null;
			this.child = null;
			return true;
		} else {
			return false;
		}
	}

	override function dispose()
	{
		index.onChange.clear();
		index = _index = null;
		if (null != child)
			child.dispose();
		child = null;
		super.dispose();
	}
}